<template>
	<view class="video-container">
		<uv-toast ref="toast"></uv-toast>
		<!-- 视频播放器 -->
		<VideoPlayer :video-info="videoInfo" @error="handleVideoError" @ended="handleVideoEnd"
			@timeupdate="handleTimeUpdate" @switch-definition="handleDefinitionSwitch" ref="videoPlayer"
			:memoryProgress="watchProgress"></VideoPlayer>

		<scroll-view scroll-y class="store-list">
			<!-- 视频信息组件 -->
			<VideoInfo :video-info="videoInfo" :course="course"></VideoInfo>
		</scroll-view>
	</view>
</template>

<script>
	import {
		formatDate
	} from '@/utils/timeParse.js';
	export default {
		data() {
			return {
				loading: true,
				param: {
					courseId: 0,
					courseMediaId: 0
				},
				courseMediaList: [],
				pageSize: 6,
				pageNumber: 1,
				courseMedia: {},
				course: {},
				videoInfo: {
					id: null,
					title: '',
					videoUrl: '',
					coverUrl: '',
					views: 0,
					createTime: '',
					description: '',
					duration: '',
					status: '',
					mediaType: '',
					definition: '',
					definitions: [],
					bitrate: '',
					size: 0,
				},
				adList: [],
				videoContext: null,
				watchProgress: 0,
				isVideoComplete: false,
				progressSaveThrottle: null,
			};
		},

		methods: {
			showToast(msg, type = 'default', duration = 2000) {
				this.$refs.toast.show({
					message: msg,
					type: type,
					duration: duration,
				})
			},
			// 处理清晰度切换
			handleDefinitionSwitch({
				definition,
				playUrl,
				currentTime
			}) {
				if (!definition || !playUrl) return;

				this.updateVideoInfo({
					videoUrl: playUrl,
					definition: definition
				});

				// 恢复播放进度
				this.$nextTick(() => {
					if (this.$refs.videoPlayer && typeof currentTime === 'number') {
						this.$refs.videoPlayer.seek(currentTime);
					}
				});
			},
			// 上传视频观看进度 在页面隐藏时请求保存到数据库
			async fetchSaveVideoProgress() {
				// 如果没有视频ID或进度，则不保存
				if (!this.courseMedia.id || typeof this.watchProgress !== 'number') {
					return;
				}

				try {
					// 构建请求参数
					const progressData = {
						courseMediaId: this.courseMedia.id,
						progress: Math.floor(this.watchProgress),
						duration: this.videoInfo.duration ? parseInt(this.videoInfo.duration) : 0,
						watchDate: formatDate(new Date(), 'YYYY-MM-DD'),
						courseId: this.course.id
					};

					// 添加验证
					if (progressData.progress < 0 || progressData.duration < 0) {
						return;
					}

					// 只有当进度大于0时才保存
					if (progressData.progress > 0) {
						const res = await this.$http.post('/user/video/progress', progressData);
					}
				} catch (e) {
					console.error('保存进度失败:', e);
					this.showToast('保存播放进度失败', 'error');
				}
			},
			// 获取课程信息
			async fetchCourseInfo() {
				if (!this.param.courseId) {
					throw new Error('课程ID不能为空');
				}

				try {
					const course = await this.$http.get(`/course/info?courseId=${this.param.courseId}`);
					if (course) {
						this.course = {
							...course,
							price: course.price ? Number(course.price).toFixed(2) : '0.00',
							originalPrice: course.originalPrice ? Number(course.originalPrice).toFixed(2) : ''
						};
					}
				} catch (e) {
					throw new Error(e.msg || '获取课程信息失败');
				}
			},

			// 获取媒资信息
			async fetchCourseMedia() {
				if (!this.param.courseMediaId) {
					throw new Error('媒资ID不能为空');
				}

				try {
					const courseMedia = await this.$http.post(`/courses/media/byId?id=${this.param.courseMediaId}`);
					if (courseMedia) {
						this.courseMedia = courseMedia;
						// 更新视频信息
						this.updateVideoInfo({
							id: courseMedia.id,
							title: courseMedia.title || '',
							coverUrl: courseMedia.coverImageUrl || '',
							description: courseMedia.des || '',
							createTime: courseMedia.createTime || '',
						});

						// 获取点播信息
						if (courseMedia.videoId) {
							await this.fetchVideoInfo(courseMedia.videoId);
						}
					}
				} catch (e) {
					throw new Error(e.msg || '获取媒资信息失败');
				}
			},

			// 获取点播信息
			async fetchVideoInfo(videoId) {
				if (!videoId) {
					throw new Error('视频ID不能为空');
				}

				try {
					const response = await this.$http.post(`/courses/media/demand?videoId=${videoId}`);
					if (!response) {
						throw new Error('获取视频信息失败：响应为空');
					}

					// 处理视频基础信息
					if (response.videoBase) {
						const videoBase = response.videoBase;
						// 检查必要字段
						if (!videoBase.Title && !this.videoInfo.title) {
							console.warn('视频标题不存在');
						}

						this.updateVideoInfo({
							coverUrl: videoBase.coverURL || this.videoInfo.coverUrl,
							createTime: videoBase.creationTime || this.videoInfo.createTime,
							duration: videoBase.duration || '',
							mediaType: videoBase.mediaType || '',
							status: videoBase.status || '',
							title: videoBase.title || this.videoInfo.title,
						});
					} else {
						console.warn('视频基础信息不存在');
					}

					// 处理播放信息
					if (Array.isArray(response.playInfo) && response.playInfo.length > 0) {
						// 过滤掉无效的播放信息
						const validPlayInfo = response.playInfo.filter(info =>
							info &&
							info.playURL &&
							info.definition &&
							info.status === 'Normal' // 确保视频状态正常
						);

						if (validPlayInfo.length === 0) {
							throw new Error('没有可用的播放源');
						}

						// 按清晰度排序，优先选择高清晰度
						const sortedPlayInfo = this.sortPlayInfoByDefinition(validPlayInfo);

						// 获取可用的清晰度列表
						const definitions = sortedPlayInfo.map(info => {
							return {
								label: this.getDefinitionLabel(info.definition),
								value: info.definition,
								bitrate: this.formatBitrate(info.bitrate),
								size: this.formatSize(info.size),
								playUrl: info.playURL // 添加播放地址
							};
						});

						// 默认选择最高清晰度
						const bestQuality = sortedPlayInfo[0];
						if (!bestQuality.playURL) {
							throw new Error('视频播放地址无效');
						}

						this.updateVideoInfo({
							videoUrl: bestQuality.playURL,
							definition: bestQuality.definition,
							definitions: definitions,
							bitrate: this.formatBitrate(bestQuality.bitrate),
							size: this.formatSize(bestQuality.size)
						});
					} else {
						throw new Error('没有可用的播放信息');
					}
				} catch (e) {
					console.error('获取视频信息失败:', e);
					throw new Error(e.msg || '获取视频信息失败');
				}
			},

			// 按清晰度排序播放信息
			sortPlayInfoByDefinition(playInfo) {
				const definitionOrder = {
					'FHD': 5, // 1080P
					'HD': 4, // 高清
					'SD': 3, // 标清
					'LD': 2, // 流畅
					'AUTO': 1 // 自动
				};

				return playInfo.sort((a, b) => {
					const orderA = definitionOrder[a.definition] || 0;
					const orderB = definitionOrder[b.definition] || 0;
					return orderB - orderA;
				});
			},

			// 获取清晰度显示标签
			getDefinitionLabel(definition) {
				const labels = {
					'FHD': '1080P',
					'HD': '高清',
					'SD': '标清',
					'LD': '流畅',
					'AUTO': '自动'
				};
				return labels[definition] || definition;
			},

			// 切换视频清晰度
			switchDefinition(definition) {
				const playInfo = this.videoInfo.definitions.find(d => d.value === definition);
				if (playInfo) {
					const currentTime = this.watchProgress;
					this.updateVideoInfo({
						videoUrl: playInfo.playUrl,
						definition: playInfo.value,
						bitrate: playInfo.bitrate,
						size: playInfo.size
					});
					// 切换后恢复播放进度
					this.$nextTick(() => {
						this.videoContext.seek(currentTime);
					});
				}
			},

			// 更新视频信息，保持已有信息不被覆盖
			updateVideoInfo(newInfo) {
				this.videoInfo = {
					...this.videoInfo,
					...Object.fromEntries(
						Object.entries(newInfo).filter(([_, value]) => value !== null && value !== undefined &&
							value !== '')
					)
				};
			},

			// 格式化视频时长
			formatDuration(duration) {
				if (!duration) return '';
				const seconds = parseInt(duration);
				const minutes = Math.floor(seconds / 60);
				const remainingSeconds = seconds % 60;
				return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`;
			},

			// 处理视频错误
			handleVideoError(e) {
				console.error('视频播放错误:', e);
				this.showToast('视频播放出错，请稍后重试', 'error');
			},

			// 处理视频播放完成
			handleVideoEnd() {
				this.isVideoComplete = true;
				// 发送视频完成事件
				this.reportVideoComplete();
			},

			// 处理视频播放进度 视频进度节流保存
			handleTimeUpdate(e) {
				if (e && e.detail && typeof e.detail.currentTime === 'number') {
					this.watchProgress = e.detail.currentTime;

					// 使用节流保存进度（每10秒最多保存一次）
					if (!this.progressSaveThrottle) {
						this.progressSaveThrottle = setTimeout(() => {
							this.fetchSaveVideoProgress();
							this.progressSaveThrottle = null;
						}, 10000);
					}
				}
			},
			async fetchProgress() {
				if (this.course.paymentRules === 0) {
					return;
				}
				try {
					const progress = await this.$http.get(`/user/video/progress/${this.courseMedia.id}`);
					if (progress && !progress.completed) {
						// 如果存在进度并且已经播放完成 则从记忆处播放
						this.watchProgress = progress.progress;
					}
				} catch (e) {
					console.error('获取播放进度失败', e);
				}
			},
			// 上报视频完成状态
			async reportVideoComplete() {
				try {
					const res = await this.$http.post(`/user/video/complete`, this.courseMedia);
					if (res) {
						this.showToast('已获得早餐券！', 'success');
						// 更新视频状态
						uni.$emit('videoComplete');
					}

					// 延迟返回上一页
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} catch (e) {
					this.showToast(e.msg || '提交观看记录失败', 'error');
				}
			},

			// 处理广告点击
			handleAdClick(ad) {
				// 处理广告点击逻辑
				console.log('广告点击:', ad);
			},

			// 初始化页面数据
			async initPageData() {
				try {
					this.loading = true;
					await this.fetchCourseInfo();
					await this.fetchCourseMedia();
					await this.fetchProgress();
				} catch (error) {
					this.showToast(error.message, 'error');
					setTimeout(() => {
						uni.navigateBack();
					}, 1500);
				} finally {
					this.loading = false;
				}
			},

			// 格式化码率
			formatBitrate(bitrate) {
				if (!bitrate) return '';
				const num = parseInt(bitrate);
				if (isNaN(num)) return bitrate;
				return `${(num / 1024).toFixed(1)}Mbps`;
			},

			// 格式化文件大小
			formatSize(size) {
				if (!size) return '';
				const num = parseInt(size);
				if (isNaN(num)) return size;
				if (num < 1024) return `${num}B`;
				if (num < 1024 * 1024) return `${(num / 1024).toFixed(1)}KB`;
				if (num < 1024 * 1024 * 1024) return `${(num / 1024 / 1024).toFixed(1)}MB`;
				return `${(num / 1024 / 1024 / 1024).toFixed(1)}GB`;
			},
		},

		computed: {
			// 格式化后的视频时长
			formattedDuration() {
				return this.formatDuration(this.videoInfo.duration);
			},

			// 解析课程标签
			parseTags() {
				return this.course.tags ? this.course.tags.split(',').filter(tag => tag.trim()) : [];
			}
		},

		async onLoad(options) {
			if (options) {
				this.param = {
					courseId: Number(options.courseId) || 0,
					courseMediaId: Number(options.courseMediaId) || 0
				};
			}

			await this.initPageData();
		},

		// 页面隐藏时保存进度
		onHide() {
			this.fetchSaveVideoProgress();
		},
		// 页面卸载方法
		onUnload() {
			// 保存进度
			this.fetchSaveVideoProgress();
			// 停止视频播放
			if (this.$refs.videoPlayer) {
				this.$refs.videoPlayer.stop();
			}
		},
		beforeDestroy() {
			if (this.progressSaveThrottle) {
				clearTimeout(this.progressSaveThrottle);
			}
		}
	}
</script>

<style lang="scss" scoped>
	@import './video_play.scss';
</style>